package com.emperor.course.app;

import java.text.DecimalFormat;
import java.util.ArrayList;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Restrictions;

import com.emperor.cashier.app.CashierAppCtrl;
import com.emperor.category.app.CategoryAppCtrl;
import com.emperor.category.logic.Category;
import com.emperor.category.logic.CategoryModel;
import com.emperor.core.app.App;
import com.emperor.core.app.AppBase;
import com.emperor.core.app.AppConstant;
import com.emperor.course.logic.Course;
import com.emperor.customer.app.CustomerAppCtrl;
import com.emperor.util.HibernateUtil;
import com.swtdesigner.SWTResourceManager;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Group;

public class CourseAppEnq extends AppBase implements App {

	protected Shell shell;
	public static Logger log = Logger.getLogger(CourseAppEnq.class);

	public CourseAppEnq() {
		super();
	}

	public CourseAppEnq(Map<String, Object> params) {
		super();
		this.params = params;
	}

	/**
	 * Launch the application
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			CourseAppEnq window = new CourseAppEnq();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window
	 */
	public void open() {
		final Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
	}

	/**
	 * Create contents of the window
	 */
	protected void createContents() {
		shell = new Shell();
		shell.setBackgroundImage(SWTResourceManager.getImage(
				CourseAppEnq.class, "/img/main.jpg"));
		shell.setImage(SWTResourceManager.getImage(CourseAppEnq.class,
				"/img/iMac OSX.png"));
		shell.setFont(SWTResourceManager.getFont("", 12, SWT.NONE));
		shell.setBackgroundMode(SWT.INHERIT_DEFAULT);
		shell.setSize(1280, 800);
		shell.setText("Search Courses");

		initScreen(shell, getParams());

		final Composite composite = new Composite(shell, SWT.NONE);
		composite.setBounds(0, 50, 1254, 104);

		final Label courseNameLabel = new Label(composite, SWT.NONE);
		courseNameLabel.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		courseNameLabel.setText("Course Name");
		courseNameLabel.setBounds(11, 55, 120, 20);

		final Text text = new Text(composite, SWT.BORDER);
		text.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI",
				12, SWT.NORMAL));
		text.setToolTipText("name");
		text.setBounds(135, 52, 320, 30);

		final Table table = new Table(shell, SWT.FULL_SELECTION | SWT.BORDER);
		table.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI",
				12, SWT.NORMAL));
		table.addMouseListener(new MouseAdapter() {
			public void mouseDoubleClick(final MouseEvent e) {
				TableItem[] items = table.getSelection();
				if (items != null && items.length > 0) {
					for (int i = 0; i < items.length; i++) {
						TableItem item = items[i];
						if (item.getData() != null) {
							Course course = (Course) item.getData();
							getParams().put(CourseAppCtrl.COURSE_ID,
									course.getId());

							getParams().put(AppConstant.APPCTRL,
									CourseAppCtrl.COURSE_CTRL);
							getParams().put(AppConstant.ACTION,
									CourseAppCtrl.COURSE_MGM);
							getShell().close();
						}
					}
				}
			}
		});
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		table.setBounds(10, 160, 1252, 438);

		final Label messageLabel = new Label(composite, SWT.NONE);
		messageLabel.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		messageLabel.setText("Please key in the course name to search.");
		messageLabel.setBounds(557, 55, 687, 20);

		final Button searchButton = new Button(composite, SWT.NONE);
		searchButton.setImage(SWTResourceManager.getImage(CourseAppEnq.class,
				"/img/Zoom-in.png"));
		searchButton.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		searchButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				populateTable(table, text, messageLabel);
			}
		});
		searchButton.setText("Search");
		searchButton.setBounds(461, 50, 90, 30);

		final TableColumn newColumnTableColumn = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn.setWidth(64);
		newColumnTableColumn.setText("No.");

		final TableColumn newColumnTableColumn_1 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_1.setWidth(397);
		newColumnTableColumn_1.setText("Name");

		final TableColumn newColumnTableColumn_2 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_2.setWidth(211);
		newColumnTableColumn_2.setText("SKU");

		final TableColumn newColumnTableColumn_3 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_3.setWidth(261);
		newColumnTableColumn_3.setText("Price");

		final Combo combo = new Combo(composite, SWT.NONE);
		combo.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI",
				12, SWT.NORMAL));
		combo.setBounds(135, 10, 411, 23);
		//		
		buildStandardMenu(getShell(), getParams(), CashierAppCtrl.CASHIER_CTRL,
				CashierAppCtrl.CASHIER_FORM);
		populateTable(table, text, messageLabel);
		populateMsg(messageLabel);
		populateCombo(combo);

		Label courseCategoryLabel = new Label(composite, SWT.NONE);
		courseCategoryLabel.setText("Course Category");
		courseCategoryLabel.setFont(org.eclipse.wb.swt.SWTResourceManager
				.getFont("Segoe UI", 12, SWT.NORMAL));
		courseCategoryLabel.setBounds(11, 10, 120, 20);

		final Button deleteButton = new Button(shell, SWT.NONE);
		deleteButton.setVisible(false);
		deleteButton.setImage(SWTResourceManager.getImage(CourseAppEnq.class,
				"/img/Symbol-Delete.png"));
		deleteButton.setBounds(177, 687, 85, 30);
		deleteButton.setFont(SWTResourceManager.getFont("", 12, SWT.NONE));
		deleteButton.setText("Delete");

		Group grpCourse = new Group(shell, SWT.NONE);
		grpCourse.setText("Course");
		grpCourse.setBounds(10, 604, 193, 55);

		final Button addNewEmployeButton = new Button(grpCourse, SWT.NONE);
		addNewEmployeButton.setBounds(10, 15, 65, 30);
		addNewEmployeButton.setImage(SWTResourceManager.getImage(
				CourseAppEnq.class, "/img/Symbol-Add.png"));
		addNewEmployeButton.setFont(org.eclipse.wb.swt.SWTResourceManager
				.getFont("Segoe UI", 12, SWT.NORMAL));
		addNewEmployeButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				getParams().put(AppConstant.APPCTRL, CourseAppCtrl.COURSE_CTRL);
				getParams().put(AppConstant.ACTION, CourseAppCtrl.COURSE_NEW);
				getShell().close();
			}
		});
		addNewEmployeButton.setText("Add");

		final Button updateEmployeeButton = new Button(grpCourse, SWT.NONE);
		updateEmployeeButton.setBounds(81, 15, 90, 30);
		updateEmployeeButton.setImage(SWTResourceManager.getImage(
				CourseAppEnq.class, "/img/Edit.png"));
		updateEmployeeButton.setFont(org.eclipse.wb.swt.SWTResourceManager
				.getFont("Segoe UI", 12, SWT.NORMAL));
		updateEmployeeButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				TableItem[] items = table.getSelection();
				if (items != null && items.length > 0) {
					for (int i = 0; i < items.length; i++) {
						TableItem item = items[i];
						if (item.getData() != null) {
							Course course = (Course) item.getData();
							getParams().put(CourseAppCtrl.COURSE_ID,
									course.getId());

							getParams().put(AppConstant.APPCTRL,
									CourseAppCtrl.COURSE_CTRL);
							getParams().put(AppConstant.ACTION,
									CourseAppCtrl.COURSE_MGM);
							getShell().close();
						}
					}
				}
			}
		});
		updateEmployeeButton.setText("Update");

		Group grpCategory = new Group(shell, SWT.NONE);
		grpCategory.setText("Category");
		grpCategory.setBounds(402, 603, 215, 55);

		Button btnAdd = new Button(grpCategory, SWT.NONE);
		btnAdd.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				getParams().put(AppConstant.APPCTRL,
						CategoryAppCtrl.CATEGORY_CTRL);
				getParams().put(AppConstant.ACTION,
						CategoryAppCtrl.CATEGORY_NEW);
				getParams().put(CategoryAppCtrl.CATEGORY_TYPE,
						Category.TYPE_COURSE);
				getShell().close();
			}
		});
		btnAdd.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		btnAdd.setImage(SWTResourceManager.getImage(CourseAppEnq.class,
				"/img/Symbol-Add.png"));
		btnAdd.setBounds(10, 15, 75, 30);
		btnAdd.setText("Add");

		Button btnUpdate = new Button(grpCategory, SWT.NONE);
		btnUpdate.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				doUpdateCategory(combo);
			}
		});
		btnUpdate.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		btnUpdate.setLocation(91, 15);
		btnUpdate.setImage(SWTResourceManager.getImage(CourseAppEnq.class,
				"/img/Edit.png"));
		btnUpdate.setSize(96, 30);
		btnUpdate.setText("Update");
	}

	public Shell getShell() {
		return shell;
	}

	public void setShell(Shell shell) {
		this.shell = shell;
	}

	public void populateTable(Table table, Text text, Label label) {
		StringBuffer sb = new StringBuffer();
		table.clearAll();
		table.removeAll();
		table.redraw();
		int count = 0;
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			String name = text.getText();
			session.beginTransaction();
			// TODO Replace with StringUtills
			List<Course> courses = new ArrayList<Course>();
			Criteria cris = session.createCriteria(Course.class);
			if (!"".equals(name.trim())) {
				cris.add(Expression.like(Course.FLD_NAME, "%" + name + "%"));
			}
			courses = cris.list();

			DecimalFormat df0 = new DecimalFormat();
			df0.applyPattern("##########.##");
			df0.setMinimumFractionDigits(0);
			df0.setMaximumFractionDigits(0);

			for (Iterator<Course> iter = courses.iterator(); iter.hasNext();) {
				Course course = iter.next();
				count++;
				TableItem item = new TableItem(table, SWT.BORDER);
				item.setText(new String[] { count + ".", course.getName(),
						course.getSku(), df0.format(course.getPrice()) });
				item.setData(course);
			}
			sb.append(count).append(" course(s) found.");
		} catch (Exception e) {
			sb.append("No result found. [").append(e.getMessage()).append("]");
			log.error(sb.toString(), e);
		}
		label.setText(sb.toString());
	}

	private void populateMsg(Label label) {
		try {
			if (getParams().get(CourseAppCtrl.COURSE_MSG) != null) {
				String msg = (String) getParams().get(CourseAppCtrl.COURSE_MSG);
				label.setText(msg);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

	private void populateCombo(Combo combo) {
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			List<Category> categories = session
					.createCriteria(CategoryModel.class)
					.add(Restrictions.eq(Category.FLD_TYPE,
							Category.TYPE_COURSE))
					.add(Restrictions.eq(Category.FLD_STATUS,
							AppConstant.STATUS_ACTIVE)).list();
			if (categories != null && !categories.isEmpty()) {
				for (Category category : categories) {
					combo.add(category.getName());
					combo.setData(category.getName(), category);
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

	private void doUpdateCategory(Combo combo) {
		try {
			if (combo.getText() != null && combo.getText().length() > 0) {
				Session session = HibernateUtil.getSessionFactory()
						.getCurrentSession();
				session.beginTransaction();

				List<Category> categories = session
						.createCriteria(CategoryModel.class)
						.add(Restrictions.eq(Category.FLD_NAME, combo.getText()))
						.list();
				if (categories != null && !categories.isEmpty()) {
					Category category = categories.get(0);
					if (category != null && category.getId() != null) {
						getParams().put(CategoryAppCtrl.CATEGORY_ID,
								category.getId());

						getParams().put(AppConstant.APPCTRL,
								CategoryAppCtrl.CATEGORY_CTRL);
						getParams().put(AppConstant.ACTION,
								CategoryAppCtrl.CATEGORY_MGM);
						getParams().put(CategoryAppCtrl.CATEGORY_TYPE,
								Category.TYPE_COURSE);
						getShell().close();
					}
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}
}
